import React, { useCallback, useEffect, useRef, useState } from "react";
import Image from "next/image";
import { countries } from "./const";
import { Country, PhoneMaskProps } from "./type";
import { globalImage } from "@/user.InterfaceLayer/constants/styles/CommonStyles";
import i18n from "@/user.InterfaceLayer/Components/I18next/i18n";
import TextAtom from "../../Atoms/Text.Atom";
import TextAtomEnum from "../../Atoms/Text.Atom/enum";

const PhoneMask: React.FC<PhoneMaskProps> = () => {
  const [isOpen, setIsOpen] = useState(false);
  const [selectedCountry, setSelectedCountry] = useState<Country>(countries[0]);
  const menuRef = useRef<HTMLDivElement>(null);

  const handleToggleDropdown = useCallback(() => {
    setIsOpen((prevIsOpen) => !prevIsOpen);
  }, []);

  const handleCountryChange = useCallback(
    (country: Country) => {
      setSelectedCountry(country);
      i18n.changeLanguage(country.lng);
      setIsOpen(false);
    },
    [setIsOpen]
  );

  const handleClickOutsideMenu = useCallback(
    (event: MouseEvent) => {
      if (menuRef.current && !menuRef.current.contains(event.target as Node)) {
        setIsOpen(false);
      }
    },
    [setIsOpen]
  );

  const handleMenuClick = useCallback((event: React.MouseEvent) => {
    event.stopPropagation(); // Stop propagation to prevent closing the menu
  }, []);

  useEffect(() => {
    document.addEventListener("mousedown", handleClickOutsideMenu);
    return () => {
      document.removeEventListener("mousedown", handleClickOutsideMenu);
    };
  }, [handleClickOutsideMenu]);

  return (
    <div
      className="relative flex gap-2 items-center"
      onClick={handleToggleDropdown}
    >
      <div className="cursor-pointer w-7 h-5">
        <Image
          src={`/icons/flags/${selectedCountry.img}`}
          alt={`Flag of ${selectedCountry.name}`}
          width={720}
          height={720}
          className={globalImage}
        />
      </div>
      <label className="cursor-pointer">
        <TextAtom
          type={TextAtomEnum.enum_h4}
          className="text-textColor font-light"
        >
          {selectedCountry.code} {selectedCountry.phoneNumber}
        </TextAtom>
      </label>
      {isOpen && (
        <div
          ref={menuRef}
          className="absolute z-10 top-8 left-0 bg-bgGen border border-borderColor rounded-md shadow-md"
          onClick={handleMenuClick}
        >
          {countries.map((country) => (
            <div
              key={country.name}
              className="flex items-center p-2 hover:bg-borderColor cursor-pointer"
              onClick={() => handleCountryChange(country)}
            >
              <div className="w-6 h-4 mr-2">
                <Image
                  src={`/icons/flags/${country.img}`}
                  alt={`Flag of ${country.name}`}
                  width={0}
                  height={0}
                  className={globalImage}
                />
              </div>
              <TextAtom
                type={TextAtomEnum.enum_h5}
                className="text-textColor font-medium"
              >
                {country.name}
              </TextAtom>
            </div>
          ))}
        </div>
      )}
    </div>
  );
};

export default React.memo(PhoneMask);
